package al.xc.common.event;

import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 事件工具类
 */
@Slf4j
public final class EventUtil {

    private static final Map<String, List<IEventListener>> PREPARED_LISTENERS = new HashMap<>(16);

    /**
     * 添加事件
     * @param type 唯一码
     * @param listener 事件
     */
    public static void addListener(String type, IEventListener listener) {
        List<IEventListener> listeners = PREPARED_LISTENERS.computeIfAbsent(type, k-> new ArrayList<>());
        listeners.add(listener);
    }

    public static void fireEvent(String type) {
        fireEvent(type, (java.lang.Object)null);
    }

    public static void fireEvent(String type, Object... obj) {

        List<IEventListener> listenerList = PREPARED_LISTENERS.get(type);
        if (null == listenerList) {
            return;
        }

        for(IEventListener listener : listenerList) {
            try {
                listener.execute(obj);
            } catch (Exception ex) {
                log.error("事件执行错误", ex);
            }
        }
    }

    private EventUtil() {

    }
}
